package com.gf.framework.mongo.lambda;

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.gf.framework.common.model.user.UserContext;
import com.gf.framework.mongo.entity.BaseEntity;
import org.springframework.data.mongodb.core.query.Update;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author gaofei
 * @date 2022/5/29 15:17
 */
public class LambdaUpdate {
    private Update update;

    public LambdaUpdate() {
        update = createUpdate();
    }

    public LambdaUpdate(String column, Object value) {
        this();
        update(column, value);
    }

    public <T> LambdaUpdate(SFunction<T, Object> column, Object value) {
        this();
        update(column, value);
    }

    public LambdaUpdate(Map<String, Object> columns) {
        this();
        columns.forEach((s, o) -> update.set(s, o));
    }

    public LambdaUpdate update(Map<String, Object> columns) {
        if (update == null) {
            update = createUpdate();
        }
        columns.forEach((s, o) -> update.set(s, o));
        return this;
    }

    public <T> LambdaUpdate update(SFunction<T, Object> column, Object value) {
        return update(MongoLambdaColumn.create().builder(column).getFieldName(), value);
    }

    public LambdaUpdate update(String column, Object value) {
        if (update == null) {
            update = createUpdate();
        }
        update.set(column, value);
        return this;
    }

    public Update getUpdate() {
        return update;
    }

    private Update createUpdate() {
        Update update = new Update();
        update.set(MongoLambdaQuery.getFieldName(BaseEntity::getUpdateTime), LocalDateTime.now());
        update.set(MongoLambdaQuery.getFieldName(BaseEntity::getUpdateUser), UserContext.getUserId());
        return update;
    }
}
